package Concurrent;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Description：
 * Author: zhangc
 * Date：2017/9/28 22:44
 */
public class Producer implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                Consumer.ProducerConsumerUtils.product();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                Consumer.ProducerConsumerUtils.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    static class ProducerConsumerUtils {
        public static Lock lock = new ReentrantLock();
        public static Condition full = lock.newCondition();
        public static Condition empty = lock.newCondition();
        public static final Queue<Integer> queue = new LinkedList<>();
        public static AtomicInteger atomicInteger = new AtomicInteger(0);

        public static void product() throws InterruptedException {
            lock.lock();
            try {
                while (queue.size() == 20)
                    full.await();
                int i = atomicInteger.incrementAndGet();
                System.out.println(Thread.currentThread().getName() + ":" + "生产者生产了一个产品：" + i);
                queue.add(i);
                empty.signalAll();
            } finally {
                lock.unlock();
            }

        }

        public static void consumer() throws InterruptedException {
            lock.lock();
            try {
                while (queue.isEmpty())
                    empty.await();
                int i = queue.remove();
                System.out.println(Thread.currentThread().getName() + ":" + "消费者消费了一个产品：" + i);
                full.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(20, new ThreadFactory());
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Producer());
            if (i % 4 == 3)
                executorService.execute(new Consumer());
        }
    }

}
